<?php

namespace app\admin\model\order;

use app\admin\model\goods\Goods;
use app\admin\model\goods\GoodsItem;
use app\admin\model\OrderRefund;
use app\admin\model\User;
use think\Db;
use think\Model;


class Sale extends Model
{

    

    

    // 表名
    protected $name = 'order_sale';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'confirm_take_time_text',
        'audit_time_text',
        'create_time_text',
        'update_time_text'
    ];
    

    



    public function getConfirmTakeTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['confirm_take_time']) ? $data['confirm_take_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getAuditTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['audit_time']) ? $data['audit_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getTypeList()
    {
        return ['0' => __('全部订单'), '1' => __('未发货'), '2' => __('已发货')];
    }

    public function getRefundTypeList()
    {
        return ['0' => __('Refund_type 0'), '1' => __('Refund_type 1')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3'), '4' => __('Status 4'), '5' => __('Status 5'),'6' => __('Status 6'), '7' => __('Status 7')];
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setConfirmTakeTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setAuditTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function getUserIdAttr($value)
    {
        if ($value)
        {
            $data = User::get($value);
        }

        return empty($value) ? '' : $data['nickname'];
    }

    public function getGoodsIdAttr($value)
    {
        if ($value)
        {
            $data = Goods::get($value);
        }
        return empty($value) ? '' : $data['name'];
    }

    public function getItemIdAttr($value)
    {
        if ($value)
        {
            $data = GoodsItem::get($value);
        }
        return empty($value) ? '' : $data['spec_value_str'];
    }

    /**
     * 退款
     */
    public function refundOrder($id,$response)
    {
        $result = [
            'data' => [],
            'msg'  => '',
            'status' => false
        ];

        $where = [];
        $where['id'] = ['eq', $id];
        $where['refund_sn'] = ['eq', $response['out_trade_no']];
        $saleData = self::where($where)->find();
        $time = time();
       if (empty($saleData))
       {
           $result['msg'] = '退款单号不存在';
           return $result;
       }
        Db::startTrans();
        try {
            self::where($where)->update([
                'status' => 6,
                'update_time' => $time
            ]);

            $refundWhere = [];
            $refundWhere['refund_sn'] = ['eq',$saleData['refund_sn']];
            $refundWhere['order_id']  = ['eq',$saleData['order_goods_id']];
            $OrderRefundData = OrderRefund::where($refundWhere)->find();

            OrderRefund::where($refundWhere)->update([
                'refund_status' => 1,
                'wechat_refund_id' => $response['refund_id'], // 退款单号
                'refund_msg'       => $response['return_msg'], // 退款返回信息
            ]);

            $OrderGoodsData = OrderGoods::get($saleData['order_goods_id']);
            $OrderGoodsData->refund_status = 3;
            $OrderGoodsData->save();
            /**
             * 退积分
             */
            $UserModel = new User();

            if ($OrderGoodsData['discounts'] > 0)
            {

                 $response = $UserModel->userIntegral($OrderRefundData['uid'], $OrderGoodsData['discounts'],$time,'7','2');
            }else{
                $response  = true;
            }
            if ($response)
            {
                $result['status'] = true;
                Db::commit();
            }
        }catch(\Exception $e){
            var_dump($e->getMessage());
            $result['msg'] = $e->getMessage();
            Db::rollback();
        }

        return $result;
    }

    public function orderData()
    {
        return $this->belongsTo('order','order_id','id',[],'LEFT')->setEagerlyType(0);
    }

    public function ordergoods()
    {
        return $this->belongsTo('orderGoods','order_goods_id','id',[],'LEFT')->setEagerlyType(0);
    }

    public function itemsku()
    {
        return $this->belongsTo('app\admin\model\goods\GoodsItem','item_id','id',[],'LEFT')->setEagerlyType(0);
    }


}
